import { NetBase } from "@ret-utils/axios-request";
import { showToast } from "vant";
import { sm3, sm4 } from "sm-crypto";
import { isInApp, syncAccLoginStatus } from "@ret-utils/bridge";

import forEach from "lodash/forEach";
const baseURL = import.meta.env.VITE_BASE_URL;
const sm3Secret = import.meta.env.VITE_SIGN_SECRET;

/**
 * 加签不加密
 * @param config
 * @param requestId
 * @returns
 * 由于url默认将参数转为字符串类型，所以get请求直接使用config.params转json字符串会跟后端使用url的参数转json字符串不匹配
 */
const getValueToString = (params: any) => {
  const newParams: Record<string, string> = {};
  forEach(params, (value, key: string) => {
    newParams[key] = value.toString();
  });
  return newParams;
};
const getSignature = (
  config: { method: string; params: any; data: any; url: string | string[]; servticketId: string },
  requestId: number
) => {
  const headerData: any = {};
  const data =
    config.method == "get"
      ? JSON.stringify(getValueToString(config.params))
      : JSON.stringify(config.data ?? "");
  const method = config.method == "get" ? "GET" : "POST";
  const msg = `secret={${sm3Secret}}data=${data}request-id={${requestId}}method={${method}}`;
  headerData.signature = sm3(msg);
  // console.log("msg----", msg, sm3(msg));
  console.log(config.method, config, JSON.parse(data), "datadata");
  headerData.ftoken =
    config.method == "get" ? config?.servticketId : JSON.parse(data)?.servticketId;
  return headerData;
};
export const http = NetBase.create({
  interceptors: {
    // 请求拦截
    beforeRequestInterceptor: (config: any) => {
      console.log(config, "config123");

      config.baseURL = baseURL;
      // 设置15秒延时
      config.timeout = 15000;
      const requestId = new Date().getTime();
      const timestamp = String(requestId).slice(0, 10);
      const { signature, ftoken } = getSignature(config, requestId);
      config.headers = {
        "Content-Type": "application/json; charset=utf-8;",
        // 加签需要的3个参数
        "request-id": requestId,
        timestamp,
        signature,
        ftoken,
      };
      // console.log("config---", config);
      return config;
    },
    // 请求错误
    requestErrorInterceptor: (error: any) => {
      error.message = "请求出错";
      console.log("error--requestErrorInterceptor", error);
      return Promise.reject(error);
    },
    // 请求成功响应处理
    responseSuccessInterceptor: (res: any) => {
      const response = res.data;
      return response;
    },
    // 请求失败响应处理
    responseFailureInterceptor: (error: any) => {
      if (error?.response) {
        const { status } = error?.response || {};
        const { message, code } = error?.response?.data || {};
        console.log("error", error, status);
        switch (code) {
          case "G4002":
          case "G4003":
          case "G3006":
          case "G2101":
            showToast({ message });
            break;
          default:
            // alert(message);
            break;
        }
        return Promise.reject(error?.response?.data);
      } else {
        // 统一错误抛出
        console.log("error--网络请求出错", error);
        error.message = "当前网络请求出错，请稍后再试";
        showToast({
          message: error.message,
        });
        // return Promise.reject(error);
      }
    },
  },
});
